package com.aitaoxue.palx.fragment;

import java.io.File;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.aitaoxue.palx.R;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseFragment;
import com.aitaoxue.palx.ui.LoginActivity;
import com.aitaoxue.palx.ui.register.GuideActivity;
import com.aitaoxue.palx.util.ImageUtil;
import com.aitaoxue.palx.widget.CircleImageView;
import com.aitaoxue.palx.widget.RevealLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

public class GuideFragment_2 extends BaseFragment {
	private static final String TAG = "ImageUtil";

	@InjectView(R.id.head_img)
	CircleImageView headImg;
	@InjectView(R.id.head_push)
	Button btn1;
	@InjectView(R.id.card_img)
	ImageView cardImg;
	@InjectView(R.id.card_push)
	Button btn2;
	@InjectView(R.id.push)
	Button push;

	private View view;

	enum TYPE {
		head, card;
	}

	private TYPE type;

	// 相机
	private static final int REQUEST_CAMERA = 1;
	// 相册截图
	private static final int REQUEST_CHOOSE = 2;
	// 截取
	private static final int REQUEST_CROP = 3;

	private Uri originalName;
	private String imagePath;
	private String cropPath = null;
	private Bitmap bitmap;
	private PopupWindow window;

	private Uri originalName2;
	private String imagePath2;
	private String cropPath2 = null;
	private Bitmap bitmap2;
	private PopupWindow window2;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_guide_2, container, false);

		ButterKnife.inject(this, view);

		initData();
		return view;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.head_img:
		case R.id.head_push:
			LayoutInflater inflater = LayoutInflater.from(getActivity());
			View popView = inflater.inflate(R.layout.popup_window_header, null);
			window = new PopupWindow(getActivity());
			window.setContentView(popView);
			window.setWidth(LayoutParams.MATCH_PARENT);
			window.setHeight(LayoutParams.WRAP_CONTENT);
			window.setFocusable(true);
			window.setAnimationStyle(R.anim.footer_menu_slide_in);
			window.setBackgroundDrawable(new ColorDrawable(0x123456));
			window.setOutsideTouchable(true);
			RevealLayout left = (RevealLayout) popView.findViewById(R.id.left);
			RevealLayout right = (RevealLayout) popView
					.findViewById(R.id.right);

			setAlpha();

			left.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 拍照
					type = TYPE.head;
					Intent takePictureIntent = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					File file = ImageUtil.getImagePath();
					Log.d(TAG, " f name: " + file.getAbsolutePath());
					imagePath = file.getAbsolutePath();
					originalName = Uri.fromFile(file);
					takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
							originalName);

					startActivityForResult(takePictureIntent, REQUEST_CAMERA);
				}
			});

			right.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 从相册选择
					type = TYPE.head;
					Intent intent = new Intent(Intent.ACTION_PICK, null);
					intent.setType("image/*");
					intent.putExtra("crop", "false");
					intent.putExtra("return-data", false);
					File file2 = ImageUtil.getImagePath();
					imagePath = file2.getAbsolutePath();
					originalName = Uri.fromFile(file2);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, originalName);
					intent.putExtra("outputFormat",
							Bitmap.CompressFormat.JPEG.toString());
					intent.putExtra("noFaceDetection", true); // no face
																// detection
					startActivityForResult(intent, REQUEST_CHOOSE);
				}
			});

			window.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					removeAlpha();
				}
			});

			window.showAtLocation(view, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.card_img:
		case R.id.card_push:
			LayoutInflater inflater2 = LayoutInflater.from(getActivity());
			View popView2 = inflater2.inflate(R.layout.popup_window_header,
					null);
			window2 = new PopupWindow(getActivity());
			window2.setContentView(popView2);
			window2.setWidth(LayoutParams.MATCH_PARENT);
			window2.setHeight(LayoutParams.WRAP_CONTENT);
			window2.setFocusable(true);
			window2.setAnimationStyle(R.anim.footer_menu_slide_in);
			window2.setBackgroundDrawable(new ColorDrawable(0x123456));
			window2.setOutsideTouchable(true);
			RevealLayout left2 = (RevealLayout) popView2
					.findViewById(R.id.left);
			RevealLayout right2 = (RevealLayout) popView2
					.findViewById(R.id.right);

			setAlpha();

			left2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 拍照
					type = TYPE.card;
					Intent takePictureIntent = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					File file = ImageUtil.getImagePath();
					imagePath2 = file.getAbsolutePath();
					originalName2 = Uri.fromFile(file);
					takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
							originalName2);

					startActivityForResult(takePictureIntent, REQUEST_CAMERA);

				}
			});

			right2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 从相册选择
					type = TYPE.card;
					Intent intent = new Intent(Intent.ACTION_PICK, null);
					intent.setType("image/*");
					intent.putExtra("crop", "false");
					intent.putExtra("return-data", false);
					File file2 = ImageUtil.getImagePath();
					imagePath2 = file2.getAbsolutePath();
					originalName2 = Uri.fromFile(file2);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, originalName2);
					intent.putExtra("outputFormat",
							Bitmap.CompressFormat.JPEG.toString());
					intent.putExtra("noFaceDetection", true); // no face
																// detection
					startActivityForResult(intent, REQUEST_CHOOSE);
				}
			});

			window2.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					removeAlpha();
				}
			});

			window2.showAtLocation(view, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.push:
			// 上传图片
			if (cropPath == null) {
				((GuideActivity) getActivity()).showToast("头像不能为空", 0, 0);
				return;
			}
			if (cropPath2 == null) {
				((GuideActivity) getActivity()).showToast("学生证不能为空", 0, 0);
				return;
			}
			((GuideActivity) getActivity()).showWaitDialog();
			// AitaoXueApi.prodFinishRegister(new File(cropPath), new File(
			// cropPath2), mHandler);
			AitaoXueApi.uploadProdHead(new File(cropPath), mHandler);
			break;
		default:
			break;
		}
	}

	@Override
	public void initView(View view) {

	}

	@Override
	public void initData() {
		headImg.setOnClickListener(this);
		cardImg.setOnClickListener(this);
		btn1.setOnClickListener(this);
		btn2.setOnClickListener(this);
		push.setOnClickListener(this);
	}

	// 将屏幕加一层透明度
	private void setAlpha() {
		WindowManager.LayoutParams lp = getActivity().getWindow()
				.getAttributes();
		lp.alpha = 0.5f;

		getActivity().getWindow().setAttributes(lp);
	}

	// 去掉屏幕的透明度
	private void removeAlpha() {
		WindowManager.LayoutParams lp = getActivity().getWindow()
				.getAttributes();
		lp.alpha = 1.0f;

		getActivity().getWindow().setAttributes(lp);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CAMERA:
			File tmpFile = null;
			if (type == TYPE.head) {
				tmpFile = new File(imagePath);
			} else {
				tmpFile = new File(imagePath2);
			}

			if (tmpFile.length() == 0) {
				tmpFile.delete();
				return;
			}
			// 拍照结束
			if (type == TYPE.head) {
				Log.d(TAG, "end :" + originalName);
				cropImageUri(originalName);
			} else {
				cropImageUri(originalName2);
			}

			break;
		case REQUEST_CHOOSE:
			File tmpFile2 = null;
			if (type == TYPE.head) {
				tmpFile2 = new File(imagePath);
			} else {
				tmpFile2 = new File(imagePath2);
			}

			if (tmpFile2.length() == 0) {
				tmpFile2.delete();
				return;
			}

			// 选择结束
			if (type == TYPE.head) {
				cropImageUri(originalName);
			} else {
				cropImageUri(originalName2);
			}
			break;
		// 截取
		case REQUEST_CROP:
			// 截取成功,进行压缩
			if (type == TYPE.head) {
				bitmap = ImageUtil.compressImgFromFile(cropPath, 150f, 150f);

				ImageUtil.compressBitmapToFile(cropPath, bitmap, 30);

				File file = new File(imagePath);
				file.delete();

				window.dismiss();
				ImageLoader.getInstance().displayImage("file:///" + cropPath,
						headImg);
			} else {
				bitmap2 = ImageUtil.compressImgFromFile(cropPath2, 640f, 480f);

				ImageUtil.compressBitmapToFile(cropPath2, bitmap2, 150);

				File file = new File(imagePath2);
				file.delete();

				window2.dismiss();
				ImageLoader.getInstance().displayImage("file:///" + cropPath2,
						cardImg);
			}

			break;
		default:
			break;
		}
	}

	private void cropImageUri(Uri uri) {
		File file = ImageUtil.getImagePath();
		Log.d(TAG, "crop:" + file.getAbsolutePath());
		if (type == TYPE.head) {
			cropPath = file.getAbsolutePath();
		} else {
			cropPath2 = file.getAbsolutePath();
		}
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("scale", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		intent.putExtra("return-data", false);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

		startActivityForResult(intent, REQUEST_CROP);
	}

	private AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// ((GuideActivity) getActivity()).hideWaitDialog();
			String res = new String(arg2);

			try {
				JSONObject json = new JSONObject(res);

				String code = json.getString("code");
				if (code.equals("0000")) {
					Toast.makeText(getActivity(), "头像上传成功", Toast.LENGTH_SHORT)
							.show();

					// Intent intent = new Intent(getActivity(),
					// MainActivity.class);
					// startActivity(intent);
					// getActivity().finish();

					AitaoXueApi.uploadStudentCard(new File(cropPath2),
							mHandler2);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			System.out.println("ehhe");
		}
	};

	private AsyncHttpResponseHandler mHandler2 = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			((GuideActivity) getActivity()).hideWaitDialog();
			String res = new String(arg2);

			try {
				JSONObject json = new JSONObject(res);
				String code = json.getString("code");
				if (code.equals("0000")) {
					Toast.makeText(getActivity(), "学生证上传成功", Toast.LENGTH_SHORT)
							.show();

					Intent intent = new Intent(getActivity(),
							LoginActivity.class);
					startActivity(intent);
					getActivity().finish();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			System.out.println("hehe");
		}
	};

}
